{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 84. Largest Rectangle in Histogram\n",
    "\n",
    "Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.\n",
    "\n",
    "<div align=\"center\">\n",
    "    <img src=\"./images/histogram.png\" width=\"20%\">\n",
    "    <Figure>Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].</Figure>\n",
    "</div>\n",
    "\n",
    "<div align=\"center\">\n",
    "    <img src=\"./images/histogram_area.png\" width=\"20%\">\n",
    "    <Figure>The largest rectangle is shown in the shaded area, which has area = 10 unit.</Figure>\n",
    "</div>\n",
    "\n",
    "    Example:\n",
    "        Input: [2,1,5,6,2,3]\n",
    "        Output: 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "from typing import List\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def largestRectangleArea(self, heights: List[int]) -> int:\n",
    "        n = len(heights)\n",
    "        left, right = [0] * n, [0] * n\n",
    "        mono_stack = list()\n",
    "\n",
    "        for i in range(n):\n",
    "            while mono_stack and heights[mono_stack[-1]] > heights[i]:\n",
    "                right[mono_stack[-1]] = i\n",
    "                mono_stack.pop()\n",
    "            left[i] = mono_stack[-1] if mono_stack else -1\n",
    "            mono_stack.append(i)\n",
    "\n",
    "        ans = max((right[i] - left[i] - 1) * heights[i] for i in range(n)) if n > 0 else 0\n",
    "        return ans\n",
    "\n",
    "S = Solution()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "heights = [2, 1, 5, 6, 2, 3]\n",
    "print(S.largestRectangleArea(heights))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}